//
//  ChatLoginUserMgr.m
//  WXIM
//
//  Created by fusuwei on 14-10-29.
//  Copyright (c) 2014年 naren. All rights reserved.
//

#import "ChatLoginUserMgr.h"
#import "YY_FMResultSet.h"
#import "PublicMacros.h"
#include "EPublicMacros.h"
#import "UcfgroupXMPPManger.h"



static BOOL initReadOnce = YES;

@implementation ChatLoginUserMgr

+(NSString *)getDbPathName
{
    NSString *userId = [UcfgroupXMPPManger sharedInstance].logRegWxUserObject.UserId;
    if (initReadOnce && (userId == nil)) {
        initReadOnce = NO;
        userId = [[NSUserDefaults standardUserDefaults]objectForKey:kMY_USER_ID];
    }
    NSString *fileName = [self truncateNSString:userId To:kXMPPmyDomain];
    NSString *isFilePathName = [NSString stringWithFormat:@"%@/%@",DATABASE_PATH,fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:isFilePathName]) {
        [fileManager createDirectoryAtPath:isFilePathName withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *filePathName = [NSString stringWithFormat:@"%@/%@%@",DATABASE_PATH,fileName,@"/wxChatIM.db"];
    if (initReadOnce) {
        WXLog(@"filePathName= %@",filePathName);
    }
    return filePathName;
}
//将某一字符从开始位置截取到指定字符处
+ (NSString *)truncateNSString:(NSString *)srcStr To:(NSString *)toStr
{
    if (srcStr == nil) {
        return nil;
    }
    NSRange range = [srcStr rangeOfString:toStr];
    NSString *str = [srcStr substringToIndex:range.location];
    return str;
}


//检查 登录用户表 是否存在
+(BOOL)checkChatLoginUserTableCreatedInDb:(YY_FMDatabase *)db
{
    BOOL worked = NO;
    NSString *createTable=@"CREATE  TABLE  IF NOT EXISTS ChatLoginUser ('UserId' VARCHAR NOT NULL UNIQUE, 'UserPassword' VARCHAR)";
    worked = [db executeUpdate:createTable];
    if (worked) {
        NSLog(@"Create ChatLoginUser's table resutl %d",worked);
    }
    
    FMDBQuickCheck(worked);
    return worked;
}

//查找UserId是否存在
+(BOOL)isFindTheLoginContactId:(NSString*)UserId isExistInTable:(NSString*)tableName
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return YES;
    };
    
    YY_FMResultSet *rs = nil;
    if ([tableName isEqualToString:@"ChatLoginUser"]) {
        rs = [db executeQuery:@"select count(*) from ChatLoginUser where UserId=?",UserId];
    }
    else
    {
        NSAssert(NO, @"Don't find the tableName ChatLoginUser");
    }
    
    while ([rs next]) {
        int count= [rs intForColumnIndex:0];
        
        if (count!=0){
            [rs close];
            return YES;
        }else
        {
            [rs close];
            return NO;
        }
    };
    [rs close];
    return YES;
}

//保存当前登录用户对象ChatLoginUser到ChatLoginUser表中
+(BOOL)saveChatLoginUser:(ChatLoginUser*)chatLoginUser
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    [self checkChatLoginUserTableCreatedInDb:db];
    
    NSString *UserId = chatLoginUser.UserId;
    NSString *UserPassword = chatLoginUser.UserPassword;
    
    //如果在表中已经存在，就更新此联系人的UserPassword
    if([self isFindTheLoginContactId:UserId isExistInTable:@"ChatLoginUser"])
    {
        BOOL retb = [self saveUpdateUserId:UserId fieldName:@"UserPassword" value:UserPassword];
        return retb;
    }
    
    //先删除所有再保存 ----目前暂时仅保存当前一个登录用户
    NSString *deleteStr = @"delete from ChatLoginUser";
    BOOL worked = [db executeUpdate:deleteStr];
    
    //否则插入此条消息
    NSString *insertStr=@"INSERT INTO ChatLoginUser ('UserId','UserPassword') VALUES (?,?)";
    worked = [db executeUpdate:insertStr,UserId,UserPassword];
    
    [db close];
    
    return worked;
}


//更新指定NSString字段
+(BOOL)saveUpdateUserId:(NSString*)UserId fieldName:(NSString*)fieldName value:(NSString*)value
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    [self checkChatLoginUserTableCreatedInDb:db];
    
    NSString *updateStr = [NSString stringWithFormat:@"update ChatLoginUser set %@=? where UserID=?",fieldName];
    
    BOOL worked = [db executeUpdate:updateStr,value, UserId];
    
    [db close];
    
    return worked;
}

//更新指定NSInteger字段
+(BOOL)saveUpdateUserId:(NSString*)UserId fieldName:(NSString*)fieldName valueInt:(NSInteger)value
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    };
    
    [self checkChatLoginUserTableCreatedInDb:db];
    
    NSString *updateStr = [NSString stringWithFormat:@"update ChatLoginUser set %@=? where UserId=?",fieldName];
    
    BOOL worked = [db executeUpdate:updateStr,[NSNumber numberWithInteger:value], UserId];
    
    [db close];
    
    return worked;
}

//删除当前登录用户对象保存的信息
+ (BOOL)deleteChatLoginUser
{
    YY_FMDatabase *db = [YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    }
    
    NSString *deleteStr = [NSString stringWithFormat:@"DELETE FROM ChatLoginUser"];
    
    BOOL worked = [db executeUpdate:deleteStr];
    
    [db close];
    
    return worked;
}

//获取当前登录用户信息
+ (ChatLoginUser *)getCurLoginUser
{
    YY_FMDatabase *db=[YY_FMDatabase databaseWithPath:[self getDbPathName]];
    if (![db open]) {
        NSLog(@"getAllContactList 数据打开失败");
        return nil;
    }
    
    [self checkChatLoginUserTableCreatedInDb:db];
    
    NSString *queryString = @"select * from ChatLoginUser";
    YY_FMResultSet *rs=[db executeQuery:queryString];
    ChatLoginUser *contact = nil;
    while ([rs next]) {
        contact = [[ChatLoginUser alloc] init];
        contact.UserId = [rs stringForColumn:@"UserId"];
        contact.UserPassword = [rs stringForColumn:@"UserPassword"];
    }
    
    [rs close];
    
    return contact;
}


@end
